package org.hepeng.workx.web.util;

import org.hepeng.workx.exception.ApplicationRuntimeException;
import org.springframework.http.MediaType;
import org.springframework.util.Assert;

import javax.servlet.ServletOutputStream;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author he peng
 */
public class HttpResponseUtils {

    private HttpResponseUtils() {}

    /**
     * 屏蔽异常的获取 {@link ServletResponse} 中的 {@link ServletOutputStream}
     * @param response {@link ServletResponse} 实例对象
     * @return 返回 {@link ServletOutputStream} 实例对象
     */
    public static ServletOutputStream getOutputStreamQuietly(ServletResponse response) {
        Assert.notNull(response , "response == null");
        ServletOutputStream outputStream;
        try {
            outputStream = response.getOutputStream();
        } catch (IOException e) {
            throw new ApplicationRuntimeException(e.getMessage() , e);
        }
        return outputStream;
    }

    /**
     * 以 Content-Type = application/json;charset=UTF-8 向客户端输出 json 格式数据.
     * @param response {@link ServletResponse} 实例对象
     * @param json 要输出给客户端的 json 数据
     */
    public static void writeAndFlushJson(ServletResponse response , String json) {
        Assert.notNull(response , "response == null");
        response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        PrintWriter printWriter = new PrintWriter(getOutputStreamQuietly(response));
        printWriter.write(json);
        printWriter.flush();
    }

    /**
     * 以 Content-Type = text/html 向客户端输出 html 格式数据.
     * @param response  {@link ServletResponse} 实例对象
     * @param html 要输出给客户端的 html 数据
     */
    public static void writeAndFlushHtml(ServletResponse response , String html) {
        Assert.notNull(response , "response == null");
        response.setContentType(MediaType.TEXT_HTML_VALUE);
        PrintWriter printWriter = new PrintWriter(getOutputStreamQuietly(response));
        printWriter.write(html);
        printWriter.flush();
    }

    /**
     * 以 Content-Type = text/xml 向客户端输出 xml 格式数据.
     * @param response  {@link ServletResponse} 实例对象
     * @param xml 要输出给客户端的 xml 数据
     */
    public static void writeAndFlushXml(HttpServletResponse response, String xml) {
        Assert.notNull(response , "response == null");
        response.setContentType(MediaType.TEXT_XML_VALUE);
        PrintWriter printWriter = new PrintWriter(getOutputStreamQuietly(response));
        printWriter.write(xml);
        printWriter.flush();
    }
}
